import React, { useState, useEffect } from 'react';
import { Table, Card, Tag, Button, Modal } from 'antd';
import { EyeOutlined } from '@ant-design/icons';
import api from '../services/api';
import dayjs from 'dayjs';

const HistoryPage = () => {
  const [loading, setLoading] = useState(false);
  const [data, setData] = useState([]);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 20,
    total: 0
  });
  const [errorModalVisible, setErrorModalVisible] = useState(false);
  const [currentErrors, setCurrentErrors] = useState([]);

  useEffect(() => {
    fetchData(1);
  }, []);

  const fetchData = async (page = 1) => {
    try {
      setLoading(true);
      const response = await api.getImportLogs({
        page,
        pageSize: pagination.pageSize
      });

      if (response.success) {
        setData(response.data.logs);
        setPagination({
          ...pagination,
          current: response.data.page,
          total: response.data.total
        });
      }
    } catch (error) {
      // 错误已在 request.js 中处理
    } finally {
      setLoading(false);
    }
  };

  const showErrors = async (id) => {
    try {
      const response = await api.getImportErrors(id);
      if (response.success) {
        setCurrentErrors(response.data.errors);
        setErrorModalVisible(true);
      }
    } catch (error) {
      // 错误已在 request.js 中处理
    }
  };

  const columns = [
    {
      title: '文件名',
      dataIndex: 'filename',
      key: 'filename'
    },
    {
      title: '总记录数',
      dataIndex: 'total_records',
      key: 'total_records',
      width: 100
    },
    {
      title: '成功',
      dataIndex: 'success_records',
      key: 'success_records',
      width: 80,
      render: (text) => <span style={{ color: '#52c41a' }}>{text}</span>
    },
    {
      title: '失败',
      dataIndex: 'failed_records',
      key: 'failed_records',
      width: 80,
      render: (text) => <span style={{ color: text > 0 ? '#ff4d4f' : '#999' }}>{text}</span>
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (status) => {
        const statusMap = {
          success: { color: 'success', text: '全部成功' },
          partial: { color: 'warning', text: '部分成功' },
          failed: { color: 'error', text: '全部失败' }
        };
        const config = statusMap[status] || { color: 'default', text: status };
        return <Tag color={config.color}>{config.text}</Tag>;
      }
    },
    {
      title: '导入时间',
      dataIndex: 'created_at',
      key: 'created_at',
      width: 180,
      render: (text) => dayjs(text).format('YYYY-MM-DD HH:mm:ss')
    },
    {
      title: '操作',
      key: 'action',
      width: 120,
      render: (_, record) => (
        record.failed_records > 0 && (
          <Button
            type="link"
            icon={<EyeOutlined />}
            onClick={() => showErrors(record.id)}
          >
            查看错误
          </Button>
        )
      )
    }
  ];

  const errorColumns = [
    {
      title: '行号',
      dataIndex: 'row',
      key: 'row',
      width: 80
    },
    {
      title: '准考证号',
      dataIndex: 'studentId',
      key: 'studentId',
      width: 120
    },
    {
      title: '姓名',
      dataIndex: 'name',
      key: 'name',
      width: 100
    },
    {
      title: '错误原因',
      dataIndex: 'reason',
      key: 'reason'
    }
  ];

  return (
    <Card title="导入历史">
      <Table
        columns={columns}
        dataSource={data}
        rowKey="id"
        loading={loading}
        pagination={{
          ...pagination,
          onChange: fetchData
        }}
      />

      <Modal
        title="错误详情"
        open={errorModalVisible}
        onCancel={() => setErrorModalVisible(false)}
        footer={null}
        width={800}
      >
        <Table
          columns={errorColumns}
          dataSource={currentErrors}
          rowKey={(record) => record.row}
          pagination={{ pageSize: 10 }}
        />
      </Modal>
    </Card>
  );
};

export default HistoryPage;
